class AvatarsController < ApplicationController
	before_filter :find_user
	before_filter :login_required, :except=>[:index]
	
	def index
		@avatars = @user.avatars
	end
	
	def edit
		@avatars = @user.avatars
		@items = (6 - @avatars.size)
		@items = 0 if @items < 0
	end
	
	def update
		unless params[:avatar][:photos].blank?
			params[:avatar][:photos].each do |k, v|
				next if k.nil? || v.blank?
				if k.to_i == 0
					v.each do |p|
						next if p.nil?
						@user.avatars.create({:uploaded_data=>p})
					end
				else
					@user.avatars.find(k).update_attributes!({:uploaded_data=>v})
				end			
			end
		end
		unless params[:avatar][:delete].blank?
			params[:avatar][:delete].each do |key|
				@user.avatars.destroy(key.to_i)
			end
		end
		
		@user.avatars.first.update_attribute(:is_main, true) if @user.avatar.nil? && !@user.avatars.empty?
		if !params[:avatar][:main].blank? && params[:avatar][:main].to_i != @user.avatar.id
			@user.avatar.update_attribute(:is_main, false)
			@user.avatars.find(params[:avatar][:main]).update_attribute(:is_main, true)
		end

		redirect
    rescue ActiveRecord::RecordInvalid
    	render :action => 'new'
	end
	
	def destroy
		@avatar = @user.avatars.find(params[:id])
		@avatar.destroy
		redirect
	end
	
	private
	
	def redirect
		redirect_to user_avatars_path(@user)
	end
	
	def find_user
		login = params[:user_id].blank? ? request.host.downcase : params[:user_id]
		@user = User.find_by_login(login)
	end
	
	def authorized?
		logged_in? && ( current_user == @user || current_user.admin? )
	end
end
